<template>
  <div class="container">
    <addMedicalProductUser ref="addMedicalProductUser" />
    <importFileView ref="importFileView" />
    <MedicalProductApply ref="MedicalProductApply" />
    <resetPassward ref="resetPassward" />
    <div class="main">
      <div class="header felx">
        <div class="header_r flex">
          <div class="flex" style="margin-right: 10px">
            <p style="color: #666; white-space: nowrap">日期：</p>
            <el-config-provider :locale="locale">
              <el-date-picker
                v-model="date"
                type="daterange"
                range-separator="到"
                unlink-panels
                style="width: 220px"
                start-placeholder="请选择日期"
                end-placeholder="请选择日期"
                @change="getList"
                clearable
                :shortcuts="shortcuts"
              />
            </el-config-provider>
          </div>
          <div class="flex" style="margin-right: 10px">
            <p style="color: #666; white-space: nowrap">所在库房：</p>
            <el-select v-model="campus" placeholder="请选择库房" @change="getList" style="width: 160px;padding-left: 10px;" clearable>
              <el-option style="padding-left: 10px;" label="全部库房" value="" />
              <el-option style="padding-left: 10px;" label="信息科库房" value="1" />
              <el-option style="padding-left: 10px;"  label="物资库房" value="2" />
            </el-select>
          </div>
          <div class="flex" style="margin-right: 10px">
            <p style="color: #666; white-space: nowrap">汇总方式：</p>
            <el-select v-model="summaryType" placeholder="请选择" @change="getList" style="width: 160px;padding-left: 10px;">
              <el-option style="padding-left: 10px;" label=" 按物资汇总" value="material" />
              <el-option style="padding-left: 10px;"  label=" 按总数汇总" value="total" />
              <el-option style="padding-left: 10px;"  label=" 按明细汇总" value="detail" />
            </el-select>
          </div>
          
          <div class="serachBox flex">
            <div class="flex">
              <p style="width: 60px">科室</p>
            </div>

            <el-select 
              v-model="searchValue" 
              filterable 
              placeholder="请选择科室"
              style="width: 200px"
              @change="getList"
              :clearable="clearable"
            >
              <el-option
              style="padding-left: 10px;"
                v-for="item in departmentList"
                :key="item.id"
                
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </div>
          <div
            class="flex"
            style="cursor: pointer; margin-left: 20px; background-color: #6f72ff; padding: 8px 15px; border-radius: 4px; color: white;"
            @click="getList"
          >
            <p>搜索</p>
          </div>
          <div
            class="flex"
            style="cursor: pointer; margin-left: 20px"
            v-loading.fullscreen.lock="fullscreenLoading"
            @click="exportHandle"
          >
            <img src="../../assets/fileFlow_add.png" />
            <p>导出报表</p>
          </div>
        </div>
      </div>
      <div class="borderBox">
        <div class="table_box">
          <el-table
            :data="list"
            border
            style="width: 100%"
            scrollTo
            :row-class-name="tableRowClassName"
            :header-cell-style="headerCellStyle"
            :row-style="tableRowStyle"
          >
            <el-table-column type="index" label="序号" width="80">
              <template #header>
                <div class="header_icon">
                  <span>序号</span>
                  <el-icon class="rotate">
                    <MoreFilled />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="createdAt" label="日期" width="120">
                            <template #header>
                                <div class="header_icon">
                                    <span>日期</span>
                                    <el-icon class="rotate">
                                        <MoreFilled />
                                    </el-icon>
                                </div>
                            </template>
                        </el-table-column> -->
            <el-table-column prop="department" label="申请科室">
              <template #header>
                <div class="header_icon">
                  <span>申请科室</span>
                  <el-icon class="rotate">
                    <MoreFilled />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="日期" v-if="summaryType=='detail'">
              <template #header>
                <div class="header_icon">
                  <span>日期</span>
                  <el-icon class="rotate">
                    <MoreFilled />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="materialName" label="名称" v-if="summaryType!='total'">
              <template #header>
                <div class="header_icon">
                  <span>名称</span>
                  <el-icon class="rotate">
                    <MoreFilled />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
           
            <el-table-column prop="total" label="领取数量">
              <template #header>
                <div class="header_icon">
                  <span>数量 ({{ totalQuantity }})</span>
                  <el-icon class="rotate">
                    <MoreFilled />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" v-if="summaryType!='total'">
              <template #header>
                <div class="header_icon">
                  <span>单价</span>
                  <el-icon class="rotate">
                    <MoreFilled />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="金额">
              <template #header>
                <div class="header_icon">
                  <span>金额 ({{ totalAmount }})</span>
                  <el-icon class="rotate">
                    <MoreFilled />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-config-provider :locale="locale">
          <div style="margin-top: 10px" class="pageBox flex">
            <!-- <el-pagination
              :total="total"
              :current-page="page"
              :page-size="pageSize"
              background
              layout="prev, pager, next, sizes"
              :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
              @size-change="changePageSize"
              @current-change="changeCurrentPage"
            /> -->
            <div class="flex">
              <!-- <p>第 {{ page }} 页</p> -->
              <p style="margin-left: 10px">共 {{ total }} 条</p>
            </div>
          </div>
        </el-config-provider>
      </div>
    </div>
  </div>
</template>
<script>
import { httpService } from "@/utils/httpService";
import { formatTime } from "@/utils/dateFormat";
import {
  ElConfigProvider,
  ElMessage,
  ElMessageBox,
  ElLoading,
} from "element-plus";
import {
  MoreFilled,
  CaretLeft,
  CaretRight,
  ArrowLeftBold,
  ArrowRightBold,
  ArrowDown,
} from "@element-plus/icons-vue";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import addMedicalProductUser from "../../components/medicalProduct/addMedicalProductUser.vue";
import importFileView from "../../components/medicalProduct/importFileView.vue";
import MedicalProductApply from "../../components/medicalProduct/MedicalProductApply.vue";
import resetPassward from "../../components/medicalProduct/resetPassward.vue";

export default {
  name: "MedicalProductLogin",
  components: {
    ElMessage,
    MoreFilled,
    resetPassward,
    ElLoading,
    ElMessageBox,
    importFileView,
    addMedicalProductUser,
    CaretLeft,
    CaretRight,
    ArrowLeftBold,
    ArrowRightBold,
    ArrowDown,
    ElConfigProvider,
    MedicalProductApply,
  },
  data() {
    return {
      page: 1,
      pageSize: 10,
      total: 0,
      list: [],
      clearable:false,
      date: this.getDefaultDateRange(),
      summaryType: 'material', // 默认按明细汇总
      campus:'',
      fullscreenLoading: false,
      searchTitle: "搜索条件",
      searchValue: "",
      selectData: {},
      mobileNumber: "",
      departmentList: [], // 科室列表
      totalAmount: 0, // 总金额
      totalQuantity: 0, // 总数量
      shortcuts: [
        {
          text: '一月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 0, 1)
            const end = new Date(now.getFullYear(), 0, 31)
            return [start, end]
          }
        },
        {
          text: '二月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 1, 1)
            const end = new Date(now.getFullYear(), 1, this.getMonthLastDay(1))
            return [start, end]
          }
        },
        {
          text: '三月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 2, 1)
            const end = new Date(now.getFullYear(), 2, 31)
            return [start, end]
          }
        },
        {
          text: '四月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 3, 1)
            const end = new Date(now.getFullYear(), 3, 30)
            return [start, end]
          }
        },
        {
          text: '五月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 4, 1)
            const end = new Date(now.getFullYear(), 4, 31)
            return [start, end]
          }
        },
        {
          text: '六月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 5, 1)
            const end = new Date(now.getFullYear(), 5, 30)
            return [start, end]
          }
        },
        {
          text: '七月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 6, 1)
            const end = new Date(now.getFullYear(), 6, 31)
            return [start, end]
          }
        },
        {
          text: '八月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 7, 1)
            const end = new Date(now.getFullYear(), 7, 31)
            return [start, end]
          }
        },
        {
          text: '九月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 8, 1)
            const end = new Date(now.getFullYear(), 8, 30)
            return [start, end]
          }
        },
        {
          text: '十月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 9, 1)
            const end = new Date(now.getFullYear(), 9, 31)
            return [start, end]
          }
        },
        {
          text: '十一月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 10, 1)
            const end = new Date(now.getFullYear(), 10, 30)
            return [start, end]
          }
        },
        {
          text: '十二月',
          value: () => {
            const now = new Date()
            const start = new Date(now.getFullYear(), 11, 1)
            const end = new Date(now.getFullYear(), 11, 31)
            return [start, end]
          }
        }
      ]
    };
  },
  create() {
    this.date = this.getDefaultDateRange();
  },
  setup() {
    return {
      locale: zhCn,
    };
  },
  computed: {},
  mounted() {
    this.getDepartmentList(); // 获取科室列表
  },
  methods: {
    getDefaultDateRange() {
      const now = new Date();
      const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      return [firstDay, lastDay];
    },
    searchEnter: function (e) {
      console.log(e);
      // 使用 which 和 keyCode 属性来解决兼容问题
      var keyCode = window.event ? e.keyCode : e.which;
      var val = e.target.value;
      if (keyCode == 13 && val) {
        this.getList();
      }
    },
    tableRowClassName({ row, rowIndex }) {
      // console.log(rowIndex);
      return rowIndex % 2 === 1 ? "warning-row" : "";
    },
    headerCellStyle() {
      return {
        background: "#f2f2f2",
      };
    },
    tableRowStyle({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return {
          background: "#F5F5F5",
        };
      }
    },
    reload() {
      this.getList();
    },
    changePageSize(size) {
      this.pageSize = size;
      this.getList();
    },
    changeCurrentPage(page) {
      this.page = page;
      this.getList();
    },
    addHandle() {
      this.$refs.addMedicalProductUser.flag = true;
      this.$refs.addMedicalProductUser.title = "添加用户";
    },

    resetHandle(id) {
      this.$refs.resetPassward.flag = true;
      this.$refs.resetPassward.form.id = id;
    },
    editHandle(id) {
      this.$refs.addMedicalProductUser.flag = true;
      this.$refs.addMedicalProductUser.title = "修改用户";
      this.$refs.addMedicalProductUser.queryById(id);
    },
    importHandle(id) {
      this.$refs.importFileView.flag = true;
      this.$refs.importFileView.url = "/javaApi/materials/importExcel";
    },
    selectHandle(value) {
      console.log(value);
      this.searchTitle = value;
    },

    getMobile(data) {
      this.selectData = data;
      this.mobileNumber = "";
      this.getBasedecrypt(this.selectData);
    },
    getBasedecrypt(object) {
      let params = new FormData();
      params.append("encryptedData", object.mobile);
      httpService("/javaApi/crypto/decrypt", params, "post").then((data) => {
        this.mobileNumber = data;
        console.log(this.mobileNumber);
      });
    },

    exportHandle() {
      this.fullscreenLoading = true;
      let params = {
        department: this.searchValue || '',
        summaryType: this.summaryType,
        campus:this.campus ||''
      };

      // 判断 date 是否有值，并添加 startTime 和 endTime
      if (this.date && this.date.length === 2) {
        params.startTime = this.formatDate(this.date[0]);
        params.endTime = this.formatDate(this.date[1]);
      }
      httpService("/javaApi/stockOut/exportReport", params, "get").then((data) => {
        this.fullscreenLoading = false;
        if (data.code == 200) {
          ElMessage.success("导出成功");
          // window.open("http://192.168.9.20" + data.message, "_blank")
          window.open(data.message, "_blank");
        } else {
          ElMessage.error("导出失败，请联系管理员!");
        }
      });
    },
    getList() {
      let params = {
        department: this.searchValue || '',
        summaryType: this.summaryType,
           campus:this.campus ||''
      };

      // 判断 date 是否有值，并添加 startTime 和 endTime
      if (this.date && this.date.length === 2) {
        params.startTime = this.formatDate(this.date[0]);
        params.endTime = this.formatDate(this.date[1]);
      }

      httpService("/javaApi/stockOut/report", params, "get").then((data) => {
    if (Array.isArray(data)) {
        this.list = data;
        this.total = data.length;
        // 计算总金额
        this.totalAmount = (this.list.reduce((sum, item) => {
            const price = Number(item.totalPrice) || 0;
            // 将浮点数转换为整数进行计算
            return sum + Math.round(price * 100);
        }, 0) / 100).toFixed(2);
        // 计算总数量
        this.totalQuantity = this.list.reduce((sum, item) => {
            return sum + (Number(item.total) || 0);
        }, 0);
    } else if (data && typeof data === 'object') {
        this.list = data.list || [];
        this.total = data.total || this.list.length;
        // 计算总金额
        this.totalAmount = (this.list.reduce((sum, item) => {
            const price = Number(item.totalPrice) || 0;
            // 将浮点数转换为整数进行计算
            return sum + Math.round(price * 100);
        }, 0) / 100).toFixed(2);
        // 计算总数量
        this.totalQuantity = this.list.reduce((sum, item) => {
            return sum + (Number(item.total) || 0);
        }, 0);
    }
});
    },
    // 格式化日期方法（转换成 `YYYY-MM-DD` 格式）
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, "0");
      const day = String(d.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    delHandle(id) {
      ElMessageBox.confirm("确定要删除本条记录吗？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          httpService(
            "/javaApi/baseTeacher/deleteById",
            "id=" + id,
            "post"
          ).then((data) => {
            if (data.code == 200) {
              ElMessage.success("删除成功");
              this.getList();
            } else {
              ElMessage.error("删除失败");
            }
          });
        })
        .catch(() => {});
    },
    // 获取科室列表
    getDepartmentList() {
      httpService(
        "/javaApi/baseDepartment/list/1/1000?flag=report",
        {
          type: 1,
          noCampus: 1,
        },
        "get"
      ).then((data) => {
        this.departmentList = data.list;
        // 如果只有一个部门，则默认选中
        if (this.departmentList && this.departmentList.length>0) {
          if(this.departmentList.length === 1){
            this.searchValue = this.departmentList[0].name;
          }else{
            this.clearable= true;
          }
        }else{
          this.clearable= false;
        }
        this.getList();

        
      });
    },
    // 获取月份最后一天（处理2月份的特殊情况）
    getMonthLastDay(month) {
      const now = new Date()
      const year = now.getFullYear()
      if (month === 1) { // 2月份
        return new Date(year, 2, 0).getDate()
      }
      return 30
    },
  },
};
</script>
<style scoped>
* {
  padding: 0;
  margin: 0;
}

.flex {
  display: flex;
  align-items: center;
}

.container {
  width: calc(100vw - 30px);
  height: calc(100vh - 30px);
  padding: 15px 15px;
  background-color: #eef7fb;
}

.main {
  width: calc(100% - 30px);
  height: calc(100% - 30px);
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
}

.header {
  height: 45px;
  /* background-color: chocolate; */
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header_btn {
  width: 99px;
  height: 32px;
  background-color: #6f72ff;
  border-radius: 5px;
  justify-content: center;
  font-size: 14px;
  color: #fff;
  margin-right: 15px;
  cursor: pointer;
}

.header_btn img {
  width: 17px;
  height: 18px;
  margin-right: 5px;
}

.serachBox {
  color: #666666;
  font-size: 14px;
  width: 340px;
  height: 36px;
  border: 1px solid #d0d0d0;
  box-sizing: border-box;
  border-radius: 20px;
}

.serachBox .flex {
  justify-content: center;
  border-right: 1px solid #d0d0d0;
  margin-right: 10px;
  padding: 0 5px 0 15px;
  color: #666666;
  cursor: pointer;
}

.serachBox input {
  height: calc(100% - 4px);
  border: none;
  flex: 1;
  outline: none;
}

.serachBox button {
  width: 80px !important;
  height: 30px;
  border-radius: 15px;
  border: none;
  background-color: #6f72ff;
  color: #fff;
  font-size: 14px;
  margin-right: 2px;
  outline: none;
}

.borderBox {
  height: calc(100% - 60px);
  border: 1px solid #dfdfdf;
  border-radius: 5px;
  box-sizing: border-box;
  margin-top: 15px;
}

.borderTop {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.assetsNum {
  margin-left: 20px;
  color: #666666;
  font-size: 14px;
}

.borderTop .flex {
  margin-right: 20px;
}

.borderTop_btn {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666666;
  margin-left: 40px;
  cursor: pointer;
}

.header_icon {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.table_box {
  width: calc(100vw - 283px);
  height: calc(100% - 53px);
  /* background-color: slategrey; */
  overflow-y: auto;
}

.el-table {
  /* margin-left: -1px; */
}

.rotate {
  transform: rotate(90deg);
}

.el-scrollbar__bar {
  z-index: 11;
  overflow-x: hidden;
  position: sticky;
}

.el-table.el-table--border {
  overflow: unset;
}

.pageBox {
  background-color: #f6f6f6;
  padding: 5px 0;
  border-top: 1px solid #e7e7e7;
  border-radius: 0 0 5px 5px;
}

.el-pagination {
  margin-left: 10px;
}

.pageBox {
  justify-content: space-between;
}

.pageBox .flex {
  color: #666;
  font-size: 14px;
  margin-right: 10px;
}

.pageBox .flex p {
  color: #666;
  font-size: 14px;
  margin-right: 20px;
}

.edit_btn {
  background-color: transparent;
  color: #007eff;
  border: none;
}

.del_btn {
  background-color: transparent;
  color: #ff0000;
  border: none;
}

.retire_btn {
  background-color: transparent;
  border: none;
  color: #007eff;
}

.face_btn {
  background-color: transparent;
  color: #ff8400;
  border: none;
}

.header_l .flex p {
  margin: 0 5px;
}

.el-tooltip__trigger:focus-visible {
  outline: unset;
}
</style>